import { Ref, isRef } from 'vue';
import { IRewardRow } from '../../utils/interface';
import { formParams } from '../../utils/paramsManager';
import { add, sum } from 'lodash';

/**
 * @param prizeFromParams 奖品的ref值
 * @param levenIndex 等级的值
 * @returns {Object} { checkStock: 校验库存;
        checkHelpNum: 校验助力人数,
        checkRequire: 校验必填，必填项会失效(后端没填写的话默认是0: => exchange_code_type和exchange_usage_type), 因此需要手动处理,
        checkExChangeFileCode: 校验兑奖码,
        checkExChangeDate: 校验时间,
        checkRedEnvelope: 校验红包,
        checkMailInfo: 校验邮寄信息
    }
 */
export const installPrizeCheckRules = (rewardRow: Ref<IRewardRow> | IRewardRow, index: Ref<number> | number) => {
    const prizeFromParams = isRef(rewardRow) ? rewardRow : { value: rewardRow };
    const levenIndex = isRef(index) ? index : { value: index };
    // 校验库存
    const checkStock = () => {
        if (!prizeFromParams.value.reward_stock) {
            return `请输入${prizeFromParams.value.reward_type === 1 ? '奖品库存' : '红包个数'}!`;
        }
    };

    // 校验助力人数
    const checkHelpNum = () => {
        if (!prizeFromParams.value.help_num) {
            return '请输入助力人数';
        }

        const lastHelpNum = formParams.reward_list[levenIndex.value - 1]?.help_num ?? 0;
        const nextPrize = formParams.reward_list[levenIndex.value + 1];
        if (prizeFromParams.value.help_num <= lastHelpNum) {
            return '阶梯助力人数需大于上级阶梯助力人数';
        }

        if (nextPrize && prizeFromParams.value.help_num >= nextPrize.help_num) {
            return '阶梯助力人数需小于下级阶梯助力人数';
        }
    };

    // 必填项会失效(后端没填写的话默认是0: => exchange_code_type和exchange_usage_type), 因此需要手动处理
    const checkRequire = (rule: any, value: any) => {
        if (!value) {
            return rule.message;
        }
    };
    // 校验兑奖码
    const checkExChangeFileCode = () => {
        // 非实物不校验
        if (prizeFromParams.value.reward_type !== 1) {
            return;
        }
        // 非兑换码方式不校验
        if (prizeFromParams.value.exchange_usage_type !== 1) {
            return;
        }
        // 非导入兑换码不校验
        if (prizeFromParams.value.exchange_code_type !== 2) {
            return;
        }
        if (!prizeFromParams.value.exchange_file_list.length) {
            return '请上传兑奖码文件';
        }

        if (
            sum(prizeFromParams.value.exchange_file_list.map(item => item.num || 0)) <
            add(prizeFromParams.value.reward_stock, prizeFromParams.value.add_stock || 0)
        ) {
            return '兑换码不能少于奖品数量';
        }
    };
    // 校验时间
    const checkExChangeDate = () => {
        if (!prizeFromParams.value.exchange_time || prizeFromParams.value.exchange_time?.length) {
            return;
        }

        if (formParams.period_type === 2) {
            if (+new Date(prizeFromParams.value.exchange_time?.[0]) < +new Date(formParams.activity_time?.[0])) {
                return '兑换期限开始时间不能小于活动开始时间';
            }
        }
    };

    // 校验红包
    const checkRedEnvelope = () => {
        // 实物类型不校验红包
        if (prizeFromParams.value.reward_type === 1) {
            return;
        }
        if (!prizeFromParams.value.red_envelope_money) {
            return '请输入红包金额';
        }

        // 普通红包通过校验
        if (prizeFromParams.value.red_envelope_type === 1) {
            return;
        }
        // 拼手气红包校验范围数量
        if (prizeFromParams.value.red_envelope_range < prizeFromParams.value.red_envelope_money) {
            return '红包最大金额不能小于红包最小金额';
        }
    };

    // 校验邮寄信息
    const checkMailInfo = () => {
        // 兑奖方式为线下邮寄才校验
        if (prizeFromParams.value.exchange_usage_type !== 2) {
            return;
        }
        if (!prizeFromParams.value.mail_info.length) {
            return '请至少选择一项邮寄信息';
        }
    };

    return {
        checkStock,
        checkHelpNum,
        checkRequire,
        checkExChangeFileCode,
        checkExChangeDate,
        checkRedEnvelope,
        checkMailInfo
    };
};

/**
 * @description 根据顶部check的方法生成一个适合form的rules校验的方法
 * @param checkFn 验证方法
 * @returns 适合form的rules校验的方法
 */
export const createPrizeValidatorFactory = (checkFn: (rule: any, value: any) => string | undefined) => {
    return (rule: any, value: any, callback: any) => {
        const errMessage = checkFn(rule, value);
        if (errMessage) {
            return callback(new Error(errMessage));
        }
        callback();
    };
};

/**
 * @description 把 installPrizeCheckRules 方法返回的值 依次使用 createPrizeValidatorFactory 转换成form表单的校验函数
 * @param checkObj installPrizeCheckRules 返回的对象
 * @returns 适合form的rules校验的方法的checkObj映射
 */
export const installPrizeValidator = (checkObj: {
    [prop: string]: (rule?: any, value?: any) => string | undefined;
}) => {
    const validatorObj: any = {};
    for (const [key, check] of Object.entries(checkObj)) {
        validatorObj[key] = createPrizeValidatorFactory(check);
    }
    return validatorObj;
};
